package com.mind.adjust.service.impl;

import com.alibaba.fastjson2.JSON;
import com.mind.adjust.domain.vo.AdjustCheckResult;
import com.mind.adjust.domain.vo.PatchCallback;
import com.mind.adjust.domain.vo.SmartCheckResultVo;
import com.mind.adjust.mapper.*;
import com.mind.adjust.task.CallbackTask;
import com.mind.api.WebServiceClient;
import com.mind.api.webservice.ShareCallbackResponse;
import com.mind.cache.service.CacheService;
import com.mind.common.exception.ServiceException;
import com.mind.common.utils.DateUtils;
import com.mind.common.utils.SecurityUtils;
import com.mind.common.utils.StringUtils;
import com.mind.common.core.domain.AjaxResult;
import com.mind.customer.mapper.*;
import com.mind.system.domain.*;
import com.mind.adjust.service.AjCheckResultService;
import com.mind.system.domain.vo.ShareCallBackVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import javax.xml.bind.JAXBException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 检查结果(AjCheckResult)表服务实现类
 *
 * @author makejava
 * @since 2024-07-28 16:43:32
 */
@Service("checkResultService")
public class AjCheckResultServiceImpl implements AjCheckResultService {
    @Autowired
    private AjCheckResultMapper checkResultMapper;

    @Resource
    private WebServiceClient webServiceClient;

    @Resource
    private AjTicketTaskMapper ticketTaskMapper;

    @Resource
    private AjTicketTypeMapper ticketTypeMapper;


    @Resource
    private AjReportResultMapper reportResultMapper;

    @Resource
    private CallbackTask callbackTask;

    @Value("${shareCenter.webServiceUrl}")
    private String webServiceUrl;

    @Resource
    private CacheService cacheService;

    @Resource
    private AjAttachCateMapper attachCateMapper;

    @Resource
    private AjObjectMapper ajObjectMapper;

    /**
     * 查询检查结果信息集合
     *
     * @param checkResult 检查结果信息
     * @return 检查结果信息集合
     */
    @Override
    public List<AjCheckResult> selectCheckResultList(AjCheckResult checkResult) {
        return checkResultMapper.selectCheckResultList(checkResult);
    }

    /**
     * 通过检查结果ID查询检查结果信息
     *
     * @param checkResultId 检查结果ID
     * @return 角色对象信息
     */
    @Override
    public AjCheckResult selectCheckResultById(Long checkResultId) {
        return checkResultMapper.selectCheckResultById(checkResultId);
    }

    /**
     * 删除检查结果信息
     *
     * @param checkResultId 检查结果ID
     * @return 结果
     */
    @Override
    public int deleteCheckResultById(Long checkResultId) {
        return checkResultMapper.deleteCheckResultById(checkResultId);
    }

    /**
     * 批量删除检查结果信息
     *
     * @param checkResultIds 需要删除的检查结果ID
     * @return 结果
     */
    @Override
    public int deleteCheckResultByIds(Long[] checkResultIds) {
        return checkResultMapper.deleteCheckResultByIds(checkResultIds);
    }

    /**
     * 新增保存检查结果信息
     *
     * @param checkResult 检查结果信息
     * @return 结果
     */
    @Override
    public int insertCheckResult(AjCheckResult checkResult) {
        return checkResultMapper.insertCheckResult(checkResult);
    }

    /**
     * 修改保存检查结果信息
     *
     * @param checkResult 检查结果信息
     * @return 结果
     */
    @Override
    public int updateCheckResult(AjCheckResult checkResult) {
        return checkResultMapper.updateCheckResult(checkResult);
    }

    @Override
    public List<AjCheckResult> selectCheckResultListByTicketId(String ticketId, Integer version) {
        if (StringUtils.isNull(version)) {
            version = checkResultMapper.selectLastVersion(ticketId);
        }
        return checkResultMapper.selectByTicketId(ticketId, version);
    }

    @Override
    public AjaxResult adjustSubmit(AdjustCheckResult adjustCheckResult) {
        if (adjustCheckResult.getCheckResultList().size() == 0) {
            throw new RuntimeException("审核结果不能为空。");
        }
        Map<String, String> map = new HashMap<String, String>() {{
            put("手工通过", "人工通过");
            put("退单据", "退回发起人");
            put("退影像", "退影像");
        }};
        String handler = adjustCheckResult.getCheckResultList().get(0).getHandlerType();
        String ticketId = adjustCheckResult.getCheckResultList().get(0).getTicketId();
        Integer version = adjustCheckResult.getCheckResultList().get(0).getVersion();
        if (map.containsKey(handler)) {
            handler = map.get(handler);
        }
        AjTicketTask ticketTask = ticketTaskMapper.selectLastVersionTask(ticketId);
        if (ticketTask == null) {
            throw new ServiceException("未找到对应的任务。");
        }
        if(ticketTask.getVersion() > version){
            throw new ServiceException("当前单据号版本号已更新，请稍后提交。");
        }
        if (adjustCheckResult.getOperate().equals("adjust") && Arrays.asList("退回发起人", "人工通过").contains(handler)) {
            ShareCallBackVo callBackVo = new ShareCallBackVo();
            callBackVo.setAuditUser(SecurityUtils.getUsername());
            callBackVo.setResult(handler);
            callBackVo.setComments(adjustCheckResult.getComments());
            callBackVo.setDate(DateUtils.getTime());
            callBackVo.setTicketId(adjustCheckResult.getCheckResultList().get(0).getTicketId());
            ticketTaskMapper.updateTicketTask(new AjTicketTask() {{
                setId(ticketTask.getId());
                setCallbackStatus(4);
                setCallbackParams(JSON.toJSONString(callBackVo));
            }});
            callbackTask.executeCallbackByTask(ticketTask);

        }
        Map<String, Integer> mapResult = new HashMap<String, Integer>() {{
            put("人工通过", 3);
            put("退影像", 5);
            put("自动通过", 6);
            put("退回发起人", 2);
        }};
        AjTicketTask task = ticketTaskMapper.selectTicketTaskByVersion(ticketId, version);
        if (task != null) {
            String finalHandler = handler;
            ticketTaskMapper.updateTicketTask(new AjTicketTask() {{
                setId(task.getId());
                setHandleUsername(SecurityUtils.getUsername());
                setHandleNickname(SecurityUtils.getLoginUser().getUser().getNickName());
                setRemark(adjustCheckResult.getComments());
                setHandelTime(new Date());
                setHandleResult(mapResult.get(finalHandler));
            }});
        }
        for (AjCheckResult checkResult : adjustCheckResult.getCheckResultList()) {
            checkResult.setSubmit(1);
            if (adjustCheckResult.getOperate().equals("adjust")) {
                checkResult.setSubmit(2);
            }
            checkResultMapper.updateCheckResult(checkResult);
        }

        return AjaxResult.success();
    }

    @Override
    public SmartCheckResultVo smartCheckList(String ticketId, Integer version) {
        if (StringUtils.isNull(version)) {
            version = checkResultMapper.selectLastVersion(ticketId);
        }
        Map<String, String> subCate = new HashMap<>();
        if (cacheService.hasKey("subCateCache")) {
            subCate = cacheService.getCacheObject("subCateCache");
        }


        SmartCheckResultVo checkResultVo = new SmartCheckResultVo();
        List<AjCheckResult> checkResultList = checkResultMapper.selectByTicketId(ticketId, version);
        Map<String, String> finalSubCate = subCate;
        checkResultList.forEach(checkResult -> {
            if (StringUtils.isNotEmpty(checkResult.getBusinessCate()) && !finalSubCate.isEmpty()) {
                checkResult.setBusinessCate(Arrays.stream(checkResult.getBusinessCate().split(",")).map(item -> finalSubCate.getOrDefault(item, item)).collect(Collectors.joining(",")));
            }
                });
        checkResultVo.setResultList(checkResultList);
        AjReportResult ajReportResult = reportResultMapper.selectByTicketId(ticketId, version);
        if (StringUtils.isNotNull(ajReportResult)) {
            AjTicketTask ticketTask = ticketTaskMapper.selectTicketTaskByVersion(ticketId, version);
            List<AjObject> ajObjectList = ajObjectMapper.selectObjectList(new AjObject() {{
                setTicketType(ticketTask.getTicketType());
                setType("OriginalOrder");
            }});
            if (!org.springframework.util.CollectionUtils.isEmpty(ajObjectList)) {
                ajReportResult.setOriginalField(ajObjectList.get(0).getName());
                ajReportResult.setTicketType(ajObjectList.get(0).getName());
            }
            // 20250414update
            /*
            List<AjTicketType> ajTicketTypes = ticketTypeMapper.selectTicketTypeList(new AjTicketType() {{
                setCode(ticketTask.getTicketType());
            }});
            if (!org.springframework.util.CollectionUtils.isEmpty(ajTicketTypes)) {
                ajObjectList.get(0).getName()
            }*/

            ajReportResult.setHandleResult(ticketTask.getHandleResult());
            ajReportResult.setCompleteTime(ticketTask.getCompleteTime());
        }
        checkResultVo.setReportResult(ajReportResult);
        return checkResultVo;
    }

    @Override
    public AjaxResult patchCallback(PatchCallback patchCallback) {
        Boolean isCallback =  cacheService.getCacheObject("isCallback");
        if(StringUtils.isNotNull(isCallback) && isCallback){
            return AjaxResult.error("回调任务正在处理,请稍后重试");
        }
        callbackTask.executeCallbackTask(1);
        return AjaxResult.success();
    }

}
